package com.bdqn.crm.service.impl;


import com.bdqn.crm.entity.User;
import com.bdqn.crm.repository.UserRepository;
import com.bdqn.crm.service.UserService;
import jakarta.annotation.Resource;
import jakarta.persistence.criteria.Predicate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserRepository userRepository;

    /**
     * 多条件分页查询
     *
     * @param param
     * @param pageable
     * @return
     */
    @Override
    public Page<User> findPageByMap(Map param, Pageable pageable) {
        log.debug("多条件分页查询，参数：{}", param.toString());
        return userRepository.findAll((Specification<User>) (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (param.get("usrName") != null) { // 动态SQL
                predicates.add(cb.like(root.get("usrName"), "%" + param.get("usrName") + "%"));
            }
            if (param.get("roleId") != null) {
                predicates.add(cb.equal(root.get("usrRoleId"), param.get("roleId")));
            }
            return cb.and(predicates.toArray(new Predicate[0]));
        }, pageable);
    }

}
